<template>
    <div class="circle-wrapper" ref="circleWrapper">
      <svg width="100%" height="100%" viewBox="0 0 128 128" version="1.1" xmlns="http://www.w3.org/2000/svg"
        xmlns:xlink="http://www.w3.org/1999/xlink">
        <circle v-if="showCircle" class="circle-full" cx="66" cy="66" r="55" fill="none" :stroke="chartPercentage.color"
          stroke-width="10" stroke-linecap="round" />
        <circle v-if="showCircle" class="circle-detail" cx="66" cy="66" r="55" fill="none" stroke-width="10"
          stroke-linecap="round" :stroke="res.color" stroke-dasharray="0,10000" />
      </svg>
      <p class="coupon-num had-percent" :style="{ color: chartPercentage.color }">
        已抢
        <span class="percent" ref="percent">1%</span>
      </p>
    </div>
  </template>
  <!-- https://juejin.cn/post/6844903857030430734 -->
  <script>
  export default {
    name: "percentage",
    data() {
      return {
        chartPercentage: {},
        showCircle: true
      };
    },
    props: ['res'],
    watch: {
      res: {
        handler(val) {
          console.log(val)
          this.chartPercentage = val
          this.circle()
        },
        deep: true
      },
  
      // res(val) {
      //   this.chartPercentage = val
      //   this.circle()
      //   console.log(val)
      //   this.showCircle = false
      //   setTimeout(() => {
      //     this.showCircle = true
      //   })
      // }
    },
    methods: {
      circle() {
        var cricleEl = this.$refs.circleWrapper
        var percentEl = this.$refs.percent
        var circleLength = Math.floor(2 * Math.PI * 55);
        let percent = (this.chartPercentage.used / this.chartPercentage.limit * 100).toFixed()
        rotateCircle(cricleEl, percent)
        percentEl.innerHTML = percent + '%'
        function rotateCircle(el, percent) {
          var val = parseFloat(percent).toFixed(2);
          console.log(circleLength)
          console.log(circleLength * val / 100)
          // val = Math.max(0, val);
          // val = Math.min(100, val);
          el.setAttribute("stroke-dasharray", "" + circleLength * val / 100 + ",10000");
        }
      }
    },
    mounted() {
      this.chartPercentage = this.res
      this.circle()
  
    },
  };
  </script>
  <style lang="less" scoped>
  .circle-wrapper {
    display: block;
    position: relative;
    width: 132px;
    height: 132px;
    margin: 5px auto;
  }
  
  .circle-wrapper .coupon-num {
    width: 36px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -18px;
    color: #FF4437;
    font-size: 12px;
    margin-top: -20px;
    text-align: center;
  
    .percent {
      text-align: center;
    }
  }
  
  .circle-full {
    opacity: .2;
  }
  
  .circle-detail {
    -webkit-transform-origin: 66px 66px;
    transform-origin: 66px 66px;
    -webkit-transform: rotate(-90deg);
    transform: rotate(-90deg);
    // stroke: #FF4437;
  }
  </style>
  